package com.neusoft.service.impl;

import com.neusoft.mapper.RedemptionRecordMapper;
import com.neusoft.po.Points;
import com.neusoft.po.Product;
import com.neusoft.po.RedemptionRecord;
import com.neusoft.service.PointsService;
import com.neusoft.service.ProductService;
import com.neusoft.service.RedemptionRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RedemptionRecordServiceImpl implements RedemptionRecordService {

    @Autowired
    private PointsService pointsService;

    @Autowired
    private ProductService productService;

    @Autowired
    private RedemptionRecordMapper redemptionRecordMapper;

    @Override
    public void redeemProduct(String userId, Integer productId) {
        // 检查用户是否有足够的积分
        Integer totalAvailablePoints = pointsService.getTotalAvailablePoints(userId);
        Product product = productService.getProductById(productId);
        if (product == null) {
            throw new IllegalArgumentException("Product not found");
        }
        if (totalAvailablePoints < product.getPointCost()) {
            throw new IllegalArgumentException("Insufficient points");
        }

        // 使用积分
        pointsService.usePoints(userId, product.getPointCost());

        // 记录兑换记录
        RedemptionRecord record = new RedemptionRecord();
        record.setUserId(userId);
        record.setProductId(productId);
        record.setProductName(product.getProductName());
        record.setPointCost(product.getPointCost());
        record.setRedemptionDate(new Date().toString());
        redemptionRecordMapper.insertRedemptionRecord(record);
    }

    @Override
    public List<RedemptionRecord> getRedemptionRecordsByUserId(String userId) {
        return redemptionRecordMapper.getRedemptionRecordsByUserId(userId);
    }
}